# -*- coding:utf-8 -*-
# @FileName  :词云.py
# @Time      :2024/11/19 09:53
# @Author    :lin


from collections import Counter
import PIL.Image as Image
import jieba
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import colors
from wordcloud import WordCloud

# 读取数据
file_path = "上海旅游景点.xlsx"
df = pd.read_excel(file_path, )
specified_column = df['关键词1'].astype(str).tolist()
# print(specified_column)
# 分词
word_list = [jieba.lcut(i) for i in specified_column]
# print(word_list)
with open('stopwords.txt', 'r', encoding='utf-8') as f:
    stopwords = set(f.readlines())
stop_words = set([item.strip() for item in stopwords])

for i in range(len(word_list)):
    # 去停用词，去/n等特殊符号
    word_list[i] = [j for j in word_list[i] if j not in stop_words and len(j) > 1 and j != '/n']
    # 去空值

# 转换成一维列表并取空值
word_list = [i for j in word_list for i in j if i != '']
# 统计高频词汇
result = Counter(word_list).most_common(200)  # 词的个数

# 建立词汇字典
content = dict(result)
# 输出词频统计结果
for i in range(50):
    word, flag = result[i]
    print("{0:<10}{1:>5}".format(word, flag))

# 设置png掩膜（yourfile.png根据实际路径进行替换）
background = Image.open("img.png")
mask = np.array(background)

# 设置字体
font = r'C:\Windows\Fonts\simhei.ttf'
# 设置字体大小
max_font_size = 200
min_font_size = 10

# 建立颜色数组，可更改颜色
color_list = ['#FF274B']
# 调用颜色数组
colormap = colors.ListedColormap(color_list)

# 生成词云
wordcloud = WordCloud(scale=4,  # 输出清晰度
                      font_path=font,  # 字体路径
                      colormap=colormap,  # 字体颜色
                      width=1600,  # 输出图片宽度
                      height=900,  # 输出图片高度
                      background_color='white',  # 图片背景颜色
                      stopwords=stopwords,  # 停用词
                      mask=mask,  # 掩膜
                      max_font_size=max_font_size,  # 最大字体大小
                      min_font_size=min_font_size)  # 最小字体大小
wordcloud.generate_from_frequencies(content)

# 使用 matplotlib 显示词云
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
# 保存词云图
wordcloud.to_file("wordcloud.png")
